package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.service.goods.ImportService;
import com.qingcheng.service.goods.SkuService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportServiceImpl implements ImportService {

    @Reference
    private SkuService skuService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    public int importSkuAll() {
        int status=0;

        BulkResponse bulk = null;
        try {
            Map searchMap = new HashMap();
            searchMap.put("status",0);
            PageResult<Sku> page = skuService.findPage(status, 100);
            List<Sku> skuList = page.getRows();
            BulkRequest bulkRequest = new BulkRequest();
            for (Sku sku : skuList) {
                IndexRequest indexRequest = new IndexRequest("sku", "doc");
                Map skuMap = new HashMap();
                skuMap.put("name",sku.getName());
                skuMap.put("price",sku.getPrice());
                skuMap.put("image",sku.getImage());
                skuMap.put("createTime",sku.getCreateTime());
                skuMap.put("spuId",sku.getSpuId());
                skuMap.put("categoryName",sku.getCategoryName());
                skuMap.put("branName",sku.getBrandName());
                Map specMap = JSON.parseObject(sku.getSpec());
                skuMap.put("spec",specMap);
                skuMap.put("saleNum",sku.getSaleNum());
                skuMap.put("commentNum",sku.getCommentNum());
            }
            bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        status=bulk.status().getStatus();
        String s = bulk.buildFailureMessage();
        System.out.println(status+"----------"+s);
        return 0;
    }
}
